<?php

declare(strict_types=1);

namespace app\common\model;

use app\api\model\UserCareProduct;
use app\api\model\UserNotLikeProduct;
use think\Model;

/**
 * @mixin \think\Model
 */
class Product extends BaseModel
{

    public function productCombo()
    {
        return $this->hasMany(ProductAndCombo::class, 'product_id');
    }


    public function nav()
    {
        return $this->belongsTo(Navigation::class, 'nav_one_id')->field('id,title,alias_title,alias_title_en');
    }

    public function navOne()
    {
        return $this->belongsTo(Navigation::class, 'nav_one_id');
    }

    //收藏表
    public function careProduct()
    {
        return $this->hasOne(UserCareProduct::class, 'product_id');
    }

    public function notLikeProduct()
    {
        return $this->hasOne(UserNotLikeProduct::class, 'product_id');
    }


    //新增之后
    public static function onAfterInsert($model)
    {
        if(!empty($model->combo_id)){
            $combo_ids = json_decode($model->combo_id,true);
            $combo = new ProductAndCombo;
            $new_arr = [];
            foreach ($combo_ids as $key => $id) {
                $new_arr[] = ['combo_id' => $id, 'product_id' => $model->id];
            }
            $combo->saveAll($new_arr);
        }
      
    }


    //更新之后
    public static function onAfterUpdate($model)
    {
        if(!empty($model->combo_id)){
            $combo_ids = json_decode($model->combo_id,true);
            $combo = new ProductAndCombo;
            $res = $combo->where('product_id',$model->id)->select()->toArray();
            foreach ($res as $k => $v) {
                $combo->where('id',$v['id'])->delete();
            }
            $new_arr = [];
            foreach ($combo_ids as $key => $id) {
                $new_arr[] = ['combo_id' => $id, 'product_id' => $model->id];
            }
            $combo->saveAll($new_arr);
        }
      
    }
}
